﻿$(document).ready(function () {

    //Add section
    $('.group').click(function () {
        viewGroupModel.GroupId(0);
        viewGroupModel.GroupType("group");
        viewGroupModel.GroupTitle("");

        $('#fancybox-overlay').show();
        $('#addeditGroup').showPopup({
            width: 450
        });
    });

    // Add Group
    $('.sections').click(function () {
        $('#groupId').val('');
        var relName = $(this).attr("rel");
        var title = $(this).attr("title");

        if (relName.indexOf("group") > -1) {
            viewGroupModel.GroupId(relName.replace('group', ''));
            viewGroupModel.GroupType("section");
            viewGroupModel.GroupTitle(title);
        }

        $('#fancybox-overlay').show();
        $('#addeditGroup').showPopup({
            width: 450
        });
    });

    //Add Fields
    $('.fields').click(function () {
        $('#fieldId').val('');
        var relName = $(this).attr("rel");
        var title = $(this).attr("title");
        var values = relName.replace('group', '').split("_");

        //console.log(values);
        var group = viewFieldModel.GroupId();

        if (values.length > 1) {
            viewFieldModel.GroupId(values[0]);
            viewFieldModel.SectionId(values[1]);
        }
        else if (values.length == 1) {
            viewFieldModel.GroupId(values[0]);
            viewFieldModel.SectionId(0);
        }
        // set default values
        viewFieldModel.FieldId(0);
        viewFieldModel.FieldTitle("");
        viewFieldModel.FieldTypeId(viewFieldModel.FieldTypeOptions()[0].ID);
        viewFieldModel.VisibilityId(1);
        viewFieldModel.Tooltip("");
        viewFieldModel.Required(false);
        viewFieldModel.Printable(false);
        viewFieldModel.Filterable(false);

        // refresh object
        if (group != viewFieldModel.GroupId()) {
            console.log("change");
            var tempEl = document.getElementById("GroupId");
            if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
            jcf.customForms.replaceElement("GroupId");
            setTimeout("jcf.customForms.replaceElement('GroupId')", 0);
        }

        var tempEl2 = document.getElementById("SectionId");
        if (typeof tempEl2.jcf != "undefined" && tempEl2.jcf) tempEl2.jcf.destroy();
        jcf.customForms.replaceElement("SectionId");
        setTimeout("jcf.customForms.replaceElement('SectionId')", 0);

        /**/

        $('#fancybox-overlay').show();
        $('#addeditField').showPopup({
            width: 650
        });
    });

    //Update Fields
    $('.visibility').click(function () {
        var tagName = $(this);
        var id = tagName.attr("rel").replace('field', '');
        UpdateVisible(id, tagName);
    });
    $('.print').click(function () {
        var tagName = $(this);
        var id = tagName.attr("rel").replace('field', '');
        UpdatePrintable(id, tagName);
    });

    $('.items').click(function () {
        var tagName = $(this);
        var id = tagName.attr("rel").replace('field', '');
        viewItemModel.FieldId(id);

        // Load items on this field
        // Request ajax to get field information
        openProcess();
        $.ajax({
            type: "POST",
            url: "/FieldSetup/GetItemByField",
            data: { "id": id },
            dataType: "json",
            success: function (model, textStatus, jqXHR) {
                // Stop progress bar
                hideProcess();

                if (model != undefined && model != null)
                    viewItemModel.ItemList(model);

                // Open edit form
                $('#fancybox-overlay').show();
                $('#addEditItems').showPopup({
                    width: 600
                });
            },
            error: function (xhr, status, error) {
                // Stop progress bar
                hideProcess();
                showPopupError();
            }
        });
    });


    // Delete Fields
    $('.delete').click(function () {
        $('#groupId').val('');
        $('#fieldId').val('');
        var relName = $(this).attr("rel");
        var title = $(this).attr("title");

        if (relName.indexOf("group") > -1) {
            // Show delete group confirm
            $('#groupId').val(relName.replace('group', ''));
            $('#groupName').text(title);
            $('#fancybox-overlay').show();
            $('#deleteGroup').showPopup({
                width: 450
            });
        }
        else {
            // Show delete field confirm
            $('#fieldId').val(relName.replace('field', ''));
            $('#fieldName').text(title);
            $('#fancybox-overlay').show();
            $('#deleteField').showPopup({
                width: 450
            });
        }
    });

    //Edit/Add group/section fields
    $('.edit').click(function () {
        $('#groupId').val('');
        var relName = $(this).attr("rel");
        var title = $(this).attr("title");

        if (relName.indexOf("group") > -1) {
            // Show delete group confirm
            var groupId = relName.replace('group', '');
            viewGroupModel.GroupId(groupId);
            viewGroupModel.GroupType("edit");
            viewGroupModel.GroupTitle(title);

            $('#fancybox-overlay').show();
            $('#addeditGroup').showPopup({
                width: 450
            });
        }
        else {
            // Show delete field confirm
            var fieldId = relName.replace('field', '');
            $('#fieldId').val(fieldId);
            $('#fieldName').text(title);

            // Request ajax to get field information
            //openProcess();
            $.ajax({
                type: "POST",
                url: "/FieldSetup/GetFieldInfo",
                data: { "id": fieldId },
                dataType: "json",
                success: function (model, textStatus, jqXHR) {
                    // Stop progress bar
                    hideProcess();

                    // Set values
                    viewFieldModel.FieldId(model.Id);
                    viewFieldModel.FieldTitle(model.Title);
                    viewFieldModel.LeadTypeId(model.LeadTypeId);
                    viewFieldModel.FieldTypeId(model.FieldTypeId);
                    viewFieldModel.VisibilityId(model.VisibilityId);
                    viewFieldModel.GroupId(model.GroupId);
                    viewFieldModel.SectionId(model.SectionId);
                    viewFieldModel.Tooltip(model.Tooltip);
                    viewFieldModel.Required(model.Required);
                    viewFieldModel.Printable(model.Printable);
                    viewFieldModel.Filterable(model.Filterable);


                    // Refresh dropdown
                    var tempEl = document.getElementById("LeadTypeId");
                    if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
                    jcf.customForms.replaceElement("LeadTypeId");
                    setTimeout("jcf.customForms.replaceElement('LeadTypeId')", 0);

                    var tempEl = document.getElementById("FieldTypeId");
                    if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
                    jcf.customForms.replaceElement("FieldTypeId");
                    setTimeout("jcf.customForms.replaceElement('FieldTypeId')", 0);

                    var tempEl = document.getElementById("VisibilityId");
                    if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
                    jcf.customForms.replaceElement("VisibilityId");
                    setTimeout("jcf.customForms.replaceElement('VisibilityId')", 0);

                    var tempEl = document.getElementById("GroupId");
                    if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
                    jcf.customForms.replaceElement("GroupId");
                    setTimeout("jcf.customForms.replaceElement('GroupId')", 0);

                    var tempEl = document.getElementById("SectionId");
                    if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
                    jcf.customForms.replaceElement("SectionId");
                    setTimeout("jcf.customForms.replaceElement('SectionId')", 0);

                    // Open edit form
                    $('#fancybox-overlay').show();
                    $('#addeditField').showPopup({
                        width: 620
                    });
                },
                error: function (xhr, status, error) {
                    // Stop progress bar
                    hideProcess();
                    showPopupError();
                }
            });

        }
    });

    // Sort items
    $('.sortorder').click(function () {
        if ($(this).attr("class").indexOf('off') > -1)
            return;

        var tagName = $(this).attr('rel');
        var titleName = $(this).attr('title');
        var values = tagName.replace('group', '').split("_");
        var id = 0;

        if (tagName.indexOf("group") > -1) {
            if (values.length > 1) {
                id = values[1];
            }
            else if (values.length == 1) {
                id = values[0];
            }
            UpdateOrdered(id, "group", titleName.toLowerCase());
        }
        else {
            id = tagName.replace('field', '');
            UpdateOrdered(id, "field", titleName.toLowerCase());
        }

    });
});

// Update Order Group/Field Items
function UpdateOrdered(id, type, order) {
    var dataPost = { "id": id, "type": type, "order": order };

    // Process request
    openProcess();
    $.ajax({
        type: "POST",
        url: "/FieldSetup/UpdateOrderGroupFieldItems",
        data: dataPost,
        dataType: "json",
        success: function (model, textStatus, jqXHR) {
            hideProcess();
            if (model != null) {
                window.location = "/FieldSetup";
            }
        },
        error: function (xhr, status, error) {
            showPopupError();
        }
    });
}

// * common function */
function UpdateItems(order, id) {
    var dataPost = { "id": id, "order": order };

    // Progress
    openProcess();

    // Ajax call function
    // Handle reponse
    $.ajax({
        type: "POST",
        url: "/FieldSetup/UpdateItems",
        data: dataPost,
        dataType: "json",
        success: function (model, textStatus, jqXHR) {
            // Stop progress bar
            hideProcess();
            if (model != null) {
                viewItemModel.ItemList(model);
                // Open edit form
                $('#fancybox-overlay').show();
                $('#addEditItems').showPopup({
                    width: 600
                });
            }
        },
        error: function (xhr, status, error) {
            // Stop progress bar
            hideProcess();
            showPopupError();
        }
    });
}

function UpdateVisible(id, tagName) {
    var dataPost = { "id": id};

    // Progress
    openProcess();

    // Ajax call function
    // Handle reponse
    $.ajax({
        type: "POST",
        url: "/FieldSetup/UpdateVisible",
        data: dataPost,
        dataType: "json",
        success: function (model, textStatus, jqXHR) {
            // Stop progress bar
            hideProcess();
            tagName.text(model == "No" ? "Không" : "Có");
        },
        error: function (xhr, status, error) {
            // Stop progress bar
            hideProcess();
            showPopupError();
        }
    });
}
function UpdatePrintable(id, tagName) {
    var dataPost = { "id": id};

    // Progress
    openProcess();

    // Ajax call function
    // Handle reponse
    $.ajax({
        type: "POST",
        url: "/FieldSetup/UpdatePrintable",
        data: dataPost,
        dataType: "json",
        success: function (model, textStatus, jqXHR) {
            // Stop progress bar
            hideProcess();
            tagName.text(model == "No" ? "Không" : "Có");
        },
        error: function (xhr, status, error) {
            // Stop progress bar
            hideProcess();
            showPopupError();
        }
    });
}
function DeleteGroup() {
    var dataPost = { "id": $('#groupId').val() };

    // Progress
    openProcess();

    // Ajax call function
    // Handle reponse
    $.ajax({
        type: "POST",
        url: "/FieldSetup/DeleteGroup",
        data: dataPost,
        dataType: "json",
        success: function (model, textStatus, jqXHR) {
            // Stop progress bar
            if (model!=undefined && model=="") {
                openProcess();
                window.location="/FieldSetup";
            }
            else {
                hideProcess();
                showPopupError();
            }
        },
        error: function (xhr, status, error) {
            // Stop progress bar
            hideProcess();
            showPopupError();
        }
    });
}

function DeleteField() {
    var dataPost = { "id": $('#fieldId').val() };

    // Progress
    openProcess();

    // Ajax call function
    // Handle reponse
    $.ajax({
        type: "POST",
        url: "/FieldSetup/DeleteField",
        data: dataPost,
        dataType: "json",
        success: function (model, textStatus, jqXHR) {
            // Stop progress bar
            if (model!=undefined && model=="") {
                openProcess();
                window.location="/FieldSetup";
            }
            else {
                hideProcess();
                showPopupError();
            }
        },
        error: function (xhr, status, error) {
            // Stop progress bar
            hideProcess();
            showPopupError();
        }
    });
}

/* Config validation */
ko.validation.configure({
    registerExtenders: true,
    messagesOnModified: true,
    insertMessages: true,
    parseInputAttributes: true,
    messageTemplate: null,
    decorateElement: true,
    errorClass: "error",
    errorMessageClass: "error-desc"
});

var viewGroupModel = new function () {
    // Group
    this.GroupTitle = ko.observable("");
    this.GroupType = ko.observable("");
    this.GroupId = ko.observable(0);

    // Add group
    this.AddGroupItems = function () {
        var dataPost = { "id": viewGroupModel.GroupId(), "title": viewGroupModel.GroupTitle(), "type": viewGroupModel.GroupType() };

        // Process request
        openProcess();
        $.ajax({
            type: "POST",
            url: "/FieldSetup/AddNewGroupSection",
            data: dataPost,
            dataType: "json",
            success: function (model, textStatus, jqXHR) {
                if (model == "") {
                    window.location = "/FieldSetup";
                }
                else {
                    showPopupError();
                }
            },
            error: function (xhr, status, error) {
                showPopupError();
            }
        });
    }
};

var viewFieldModel = new function () {
    // Fields
    this.FieldId = ko.observable(0);
    this.FieldTitle = ko.observable("");
    this.FieldTypeId = ko.observable(0);
    this.FieldTypeOptions = ko.observableArray(data.FieldType);
    this.LeadTypeId = ko.observable(0);
    this.LeadTypeOptions = ko.observableArray(data.LeadType);
    this.VisibilityId = ko.observable(1);
    this.VisibilityOptions = ko.observableArray(data.VisibilityType);
    this.Tooltip = ko.observable("");
    this.Required = ko.observable(false);
    this.Printable = ko.observable(false);
    this.Filterable = ko.observable(false);

    // Group
    this.GroupId = ko.observable(data.GroupFieldType.length == 0? 0: ko.utils.arrayFilter(data.GroupFieldType, function (option) { return option.ParentId == 0 })[0].ID);
    this.GroupOptions = ko.observableArray(ko.utils.arrayFilter(data.GroupFieldType, function (option) { return option.ParentId == 0 }));
    this.SectionId = ko.observable(0);
    this.SectionOptions = ko.observableArray([]);
    this.SectionOptionFilters = ko.computed(function () {
        var optionId = this.GroupId();
        var sections = ko.utils.arrayFilter(data.GroupFieldType, function (option) {
            return option.ParentId == optionId && optionId != 0;
        });

        this.SectionId(0);
        var list = [];
        var option = {};
        option.ID = "0";
        option.ItemName = "Select a section";
        list.push(option);

        if (sections.length > 0) {
            for(var i=0;i<sections.length;i++)
            {
                list.push(sections[i]);
            }
        }
        this.SectionOptions(list);

        // Refresh dropdown
        var tempEl = document.getElementById("SectionId");
        if (typeof tempEl.jcf != "undefined" && tempEl.jcf) tempEl.jcf.destroy();
        jcf.customForms.replaceElement("SectionId");
        setTimeout("jcf.customForms.replaceElement('SectionId')", 0);

    }, this);

    // Add Fields
    this.AddFieldItems = function () {
        var dataPost = {
            "id": viewFieldModel.FieldId(),
            "title": viewFieldModel.FieldTitle(),
            "fieldTypeId": viewFieldModel.FieldTypeId(),
            "leadTypeId": viewFieldModel.LeadTypeId(),
            "visibilityId": viewFieldModel.VisibilityId(),
            "groupId": viewFieldModel.GroupId(),
            "sectionId": viewFieldModel.SectionId(),
            "toolTip": viewFieldModel.Tooltip(),
            "required": viewFieldModel.Required(),
            "printable": viewFieldModel.Printable(),
            "filterable": viewFieldModel.Filterable()
        };

        // Process request
        openProcess();
        $.ajax({
            type: "POST",
            url: "/FieldSetup/AddNewField",
            data: dataPost,
            dataType: "json",
            success: function (model, textStatus, jqXHR) {
                if (model == "") {
                    window.location = "/FieldSetup";
                }
                else {
                    showPopupError();
                }
            },
            error: function (xhr, status, error) {
                showPopupError();
            }
        });
    }
};

var viewItemModel = new function () {
    // Group
    this.ItemTitle = ko.observable("");
    this.ItemId = ko.observable(0);
    this.FieldId = ko.observable(0);
    this.ItemList = ko.observableArray([]);

    // Add group
    this.AddItems = function () {
        var dataPost = { "id": viewItemModel.FieldId(), "title": viewItemModel.ItemTitle() };

        // Process request
        openProcess();
        $.ajax({
            type: "POST",
            url: "/FieldSetup/AddNewItems",
            data: dataPost,
            dataType: "json",
            success: function (model, textStatus, jqXHR) {
                hideProcess();
                if (model != null) {
                    viewItemModel.ItemTitle("");
                    viewItemModel.ItemList(model);
                    // Open edit form
                    $('#fancybox-overlay').show();
                    $('#addEditItems').showPopup({
                        width: 600
                    });
                }
            },
            error: function (xhr, status, error) {
                showPopupError();
            }
        });
    }

    this.UpdateItemUp = function (item) {
        UpdateItems('up', item.Id);
    }
    this.UpdateItemDown = function (item) {
        UpdateItems('down', item.Id);
    }

    this.DeleteItem = function (item) {
        var dataPost = { "id": item.Id };

        // Process request
        openProcess();
        $.ajax({
            type: "POST",
            url: "/FieldSetup/DeleteItems",
            data: dataPost,
            dataType: "json",
            success: function (model, textStatus, jqXHR) {
                hideProcess();
                if (model != null) {
                    viewItemModel.ItemList(model);
                    // Open edit form
                    $('#fancybox-overlay').show();
                    $('#addEditItems').showPopup({
                        width: 600
                    });
                }
            },
            error: function (xhr, status, error) {
                showPopupError();
            }
        });
    }
};

ko.applyBindings(viewGroupModel, document.getElementById("addeditGroup"));
ko.applyBindings(viewFieldModel, document.getElementById("addeditField"));
ko.applyBindings(viewItemModel, document.getElementById("addEditItems"));